#include<stdio.h>
#include"show_bytes.h"

int sra(int x, int k){
    /*Perform shift logically*/
    int xsrl = (unsigned) x >> k;
    int intBitSize = sizeof(int) * 8;

    int mask = 0;
    if(((unsigned)x >> (intBitSize - 1)) == 1){
        mask = -1;
        mask &= ~((1 << k) - 1);
    }

    return xsrl | mask;
}

unsigned srl(unsigned x, int k){
    /*Perform shift arithmetically*/
    unsigned xsra = (int) x >> k;
    int intBitSize = sizeof(int) * 8;

    int mask = -1;
    if((x >> (intBitSize - 1)) == 1){
        mask = 0;
        mask |= (1 << (intBitSize - k)) - 1;
    }

    return xsra & mask;
}

void shiftRight(int x, int shiftBits){

    unsigned srlval = srl((unsigned)x, shiftBits);
    int sraval = sra(x,shiftBits);

    printf(" %d\n",x);
    printf(" begin:\n");
    show_bytes((byte_pointer)&x,sizeof(int));

    printf(" shift right logically:\n");
    show_bytes((byte_pointer)&srlval,sizeof(int));

    printf(" shift right arithmetically:\n");
    show_bytes((byte_pointer)&sraval,sizeof(int));

    printf("\n\n");
}

int main(void){

    int x1 = 123;
    int x2 = -123;
    int k = 4;

    shiftRight(x1,k);
    shiftRight(x2,k);

    return 0;
}
